package com.example.android.commitcontent.ime.cores.utils;

import android.content.Context;
import android.content.SharedPreferences;

public class SPHelper {
    private static final String SP_NAME = "sp_data";

    public static void put(Context context, String key, Object value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit();
        if (value instanceof Integer)
            editor.putInt(key, (Integer) value);
        if (value instanceof Long)
            editor.putLong(key, (Long) value);
        if (value instanceof String)
            editor.putString(key, (String) value);
        editor.apply();
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(Context context, String key, T defaultValue) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        if (defaultValue instanceof String)
            return (T) sharedPreferences.getString(key, (String) defaultValue);
        if (defaultValue instanceof Integer)
            return (T) (Integer) (sharedPreferences.getInt(key, (Integer) defaultValue));
        if (defaultValue instanceof Long)
            return (T) (Long) (sharedPreferences.getLong(key, (Long) defaultValue));
        return defaultValue;
    }
}
